/*
 * bloomfilter.cpp
 *
 *  Created on: 2011-10-26
 *      Author: liujian
 */
#include"bloomfilter.h"

static size_t hash_table_size = 0;
/*最佳个数是8个*/
static const unsigned int xor_val[] = {
	0x5cee4612, 0xb5587b1c, 0xa250f2b0, 0xa3bf6d2a,
	0x7a81bd1a, 0x92888d7f, 0x1dc977c7, 0xedc96624
};

void bloom_filter_set_hash_table_size(size_t size)
{
	hash_table_size = size;
}

unsigned long string_hash(const char *string)
{
	/*this is the djb2 string hash function*/
	unsigned long result = 5381;
	unsigned char *p;

	/************************************这里能转换吗？？***/
	p = (unsigned char *)string;

	while(*p != '\0'){
		result = ((result << 5) ^ result ) ^ (*p);
		++p;
	}
	return result;
}

int bloom_filter_query(void *table_src, const char * string)
{
	unsigned int i;
	unsigned int index;
	unsigned long hash;
	unsigned long subhash;
	char *addr;
	unsigned char byte;
	unsigned char bit;

	/*将地址转换为字节类型，因为后面的地址操作都是以字节为单位*/
	addr = (char *)table_src;

	hash = string_hash(string);

	for (i=0; i<sizeof(xor_val); i++){

		subhash = hash ^ xor_val[i];
		index   = subhash % hash_table_size;
		byte	= addr[index / 8];
		bit     = 1 << (index % 8);
		if ((byte & bit) == 0){
			return 0;
		}
	}
	return 1;
}

void bloom_filter_insert(void *table_src, const char *string)
{
	unsigned int i;
	unsigned int index;
	unsigned long hash;
	unsigned long subhash;
	char *addr;
	/*将地址转换为字节类型，因为后面的地址操作都是以字节为单位*/
	addr = (char *)table_src;

	hash = string_hash(string);

	for (i=0; i<sizeof(xor_val); i++){

		subhash = hash ^ xor_val[i];
		index   = subhash % hash_table_size;
		addr[index / 8] |= 1 << (index % 8);
	}
}



